import Taro, { useLoad } from '@tarojs/taro';
import { Input, Text, View } from '@tarojs/components';
import { Button, Header, ScrollView, Space, Tab, TopView } from 'pd-taro-ui';
import { Form, FormItem } from 'pd-taro-form';
import { PageParams, pageTypeTexts } from './route.config';
import { useRouterData } from '@/utils/router';
import './index.scss';
import { FormikHelpers, FormikProps } from 'formik';
import { useRef, useState } from 'react';
import { object, string } from 'yup';
import { flatFormikErrors } from '@/utils/util';
import { fakeRequest } from '@/utils/request';
import { FormItemProps } from 'pd-taro-form/FormItem';
import classNames from 'classnames';

interface MyFormValues {
  email?: string;
}

const prefix = 'TODODetailPage__';
const DetailPage = () => {
  const formikRef = useRef<FormikProps<MyFormValues>>(null);
  const initialValues: MyFormValues = {
    email: '',
  };
  const router = useRouterData();
  const pageParams = router.params as PageParams;
  const { pageType } = pageParams;

  const [tabs] = useState<{ title; key }[]>([
    {
      key: 1,
      title: 'tab1',
    },
    {
      key: 2,
      title: 'tab2',
    },
  ]);
  const [activeTabKey, setActiveTabKey] = useState(tabs[0].key);

  const formItemList: FormItemProps[] = [
    {
      type: 'Input',
      name: 'email',
      label: '邮箱',
      placeholder: '请输入邮箱',
    },
  ];

  useLoad(async () => {
    if (pageType !== 'add') {
      queryDetail();
    }
  });

  // 获取详情
  const queryDetail = async () => {
    const resp = await fakeRequest({
      id: pageParams.id,
    });
    if (!resp.success) return;

    formikRef.current?.setValues({
      email: '666666',
    });
  };

  // 提交接口
  const onSubmit = async (values: MyFormValues, formikHelpers: FormikHelpers<MyFormValues>) => {
    console.log('onSubmit', values);
  };

  return (
    <TopView>
      <Header
        title={pageTypeTexts[pageType] + 'demo'}
        titleCenter
        renderRight={
          <Space row>
            {pageType !== 'look' && (
              <Button
                size='s'
                onClick={() => {
                  if (!formikRef.current!.isValid) {
                    Taro.showToast({ icon: 'none', title: flatFormikErrors(formikRef.current!.errors)[0] });
                    return;
                  }
                  formikRef.current!.submitForm();
                }}>
                提交
              </Button>
            )}
          </Space>
        }
      />
      <Tab scroll value={activeTabKey} onChange={setActiveTabKey}>
        {tabs.map(item => (
          <Tab.Item key={item.key} title={item.title} paneKey={item.key} />
        ))}
      </Tab>
      <ScrollView>
        <Form
          innerRef={formikRef}
          validationSchema={object({
            email: string().nullable().required('email不能为空'),
          })}
          initialValues={initialValues}
          onSubmit={onSubmit}
          labelWidth={240}
          direction='horizontal'>
          {({ errors, values, handleChange, submitForm, isValid, resetForm }) => {
            return (
              <View style={{ padding: 12, paddingTop: 20 }}>
                {activeTabKey === 1 && (
                  <View>
                    {formItemList.map((item, index) => (
                      <FormItem {...item} key={index} />
                    ))}
                  </View>
                )}
              </View>
            );
          }}
        </Form>
      </ScrollView>
    </TopView>
  );
};
export default DetailPage;
